接下來要來介紹,如何綁定事件,以 click 事件來舉例:
<div id="app">
<input type="text" class="form-control" v-model="text">
<button class="btn btn-primary mt-1">反轉字串</button>
<div class="mt-3">
{{ newText }}
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
text: '',
newText: ''
},
});
</script>
先在 input 欄位內綁定 data 的 text 變數newText 變數先定義起來放置在頁面上
而現在要做的是點擊 button 元素時,會把輸入在 input 欄位內的文字做反轉
這時候會產生 click 事件,我們就可以利用 v-on 指令綁定在 button 元素上
而 click 事件會觸發的 function 則寫在另外的 methods 內,如下:
<div id="app">
<input type="text" class="form-control" v-model="text">
<button class="btn btn-primary mt-1" v-on:click="reverseText">反轉字串</button>
<div class="mt-3">
{{ newText }}
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
text: '',
newText: ''
},
methods: {
reverseText: function(){
consle.log('HELLO');
}
}
});
</script>
與以往不同的是,Vue 的結構不再只有 el 和 data 還多了 methods,事件觸發的 function 就定義在這裡面
而 button 元素綁定 v-on 指令且為 click 事件,值則為觸發的 function 名字
這時候我們可以用 console 來檢查一下,是否為正確執行
正確執行之後我們可以針對反轉字串的相關方法寫進去 function 內:
<script>
var app = new Vue({
el: '#app',
data: {
text: '',
newText: ''
},
methods: {
reverseText: function(){
this.newText = this.text.split('').reverse().join('');
}
}
});
</script>
比較值得注意的是,如果我們要讀取 data 內的資料時,需使用 this 這個關鍵字,再讀取他們的屬性
至於 .split('').reverse().join(''); 就是反轉字串的方法